var lastFileId


function setPassword() {
    var selectedFile = file.getSelection()[0]
    var id = selectedFile.data.id

    Ext.MessageBox.prompt('密码', '请输入密码:', function(btn, text){
        console.log(btn)
        if (btn=="ok") {
            Ext.Ajax.request({
                url: "../file/setpassword",
                params: {id: id, password: text},
                success: function (response, opts) {
                    var res = Ext.JSON.decode(response.responseText)
                    if(!res.success) {
                        Ext.MessageBox.show({
                            title: '出错!',
                            msg:res.message,
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox["ERROR"]
                        });
                    } else {
                        Ext.toast('操作成功!');
                        lastFileId = res.id
                        fileStore.reload()
                    }

                }
            });
        }
    },
    this,false,selectedFile.data.password);



}

function openUpdateFileTypeWindow() {
    var selection = file.getSelection()
    var editWindow = Ext.create('Ext.window.Window', {
        title: "请选择文件类型",
        iconCls:'x-fa fa-flag',
        width: 350,
        modal:true,
        items:[
            {
                xtype:'form',
                width:'100%',
                height:'100%',
                border:false,
                margin: '5 0 0 0',

                items:[
                    {
                        xtype: 'combobox',
                        id:'updateFileTypeId',
                        labelAlign:'right',
                        allowBlank:false,
                        fieldLabel:'文件类型'
                    }
                ],
                buttons: [
                    {
                        xtype: 'button',
                        text: '取消',
                        handler: function() {
                             editWindow.close()
                        }
                    },
                    {
                         xtype: 'button',
                         formBind:true,
                         text: '确定',
                         handler: function() {

                            Ext.Ajax.request({
                                url: "../file/updatefiletype",
                                params: {
                                   fileTypeId:Ext.getCmp("updateFileTypeId").getValue(),
                                },
                                success:function(response, opts) {
                                    editWindow.close()
                                    fileStore.reload()
                                }
                            })

                           
                         }
                    }
                ]
            }
        ]
    })
    editWindow.show()
}

function sortFile(type) {
    var selectedFile = file.getSelection()[0]
    //var nodes = selectedFile.parentNode.childNodes
    if (type=="up") {
        var index = selectedFile.data.index
        var id = selectedFile.data.id
        selectedFile.parentNode.insertChild(index-1,selectedFile)
    } else {
        var index = selectedFile.data.index
        var id = selectedFile.data.id
        selectedFile.parentNode.insertChild(index+2,selectedFile)
    }

    var childNodes = selectedFile.parentNode.childNodes
    var indexs = []
    var ids = []
    for(var i=0;i<childNodes.length;i++) {
        ids.push(childNodes[i].id)
        //console.log(childNodes[i].data.text)
        indexs.push(childNodes[i].data.index)
    }
    //console.log(indexs.join(","))
    //console.log(ids.join(","))
    Ext.Ajax.request({
        url: "../file/sortfile",
        params: {ids:ids,indexs:indexs},
        success:function(response, opts) {
            //fileStore.reload()
        }
    });



}


function refreshAction() {
    var selection = file.getSelection()

    Ext.getCmp('btnFileUpload').disable()
    Ext.getCmp('btnNewDir').disable()
    Ext.getCmp('btnEditFileType').disable()
    Ext.getCmp('btnFileDelete').disable()
    Ext.getCmp('btnMoveUp').disable()
    Ext.getCmp('btnMoveDown').disable()
    Ext.getCmp('btnPassword').disable()
    Ext.getCmp('btnFileNameEdit').disable()


    if (selection.length==0) {
        //lastFileId = null
        var meetingSelection = meeting.getSelection()
        if (meetingSelection.length==0) {

        } else {
            if (meetingSelection[0].data.status==2) {

            } else {
                Ext.getCmp("btnFileUpload").enable()
                Ext.getCmp("btnNewDir").enable()
            }
        }
    } else {
        //lastFileId = selection[0].data.id

        var meetingSelection = meeting.getSelection()
        if (meetingSelection.length==0) {

        } else {
            if (meetingSelection[0].data.status==2) {

            } else {
                Ext.getCmp("btnFileUpload").enable()
                Ext.getCmp("btnNewDir").enable()
                Ext.getCmp('btnFileDelete').enable()
                Ext.getCmp('btnEditFileType').enable()
                if (selection.length==1) {
                    Ext.getCmp('btnMoveDown').enable()
                    Ext.getCmp('btnMoveUp').enable()
                    Ext.getCmp('btnPassword').enable()
                    Ext.getCmp('btnFileNameEdit').enable()
                }  else {

                }

                for (var i=0;i<selection.length;i++) {
                    console.log(selection[i].data)
                    if (selection[i].data.isDir) {
                        Ext.getCmp('btnEditFileType').disable()
                        break
                    }
                }
            }
        }

    }
}


function checkFileType(filename,typeRegEx){
    if (filename.length < 4 || typeRegEx.length < 1) return false;
    var filenameParts = filename.split('.');
    if (filenameParts.length < 2) return false;
    var fileExtension = filenameParts[filenameParts.length - 1];
    // 2017-08-11 10:23 add by huangwei 
    if (fileExtension.toLowerCase()=="zip"||fileExtension.toLowerCase()=="zip") {
        return false;
    } else {
        return typeRegEx.test('.' + fileExtension);
    }
    
}

var myFLag = 0

var totalSuccessFile = 0

var fileStore = Ext.create("Ext.data.TreeStore",{
    autoLoad:true,
    listeners:{
        load :function( obj, records, successful, operation, node, eOpts ) {
            file.expandAll()

            refreshAction()
            console.log(lastFileId)
            if (lastFileId==null) {
                file.getSelectionModel().select(0)
                file.getSelectionModel().deselect(0)
            } else {
                var lastFileNode = fileStore.findNode('id',lastFileId)
                file.getSelectionModel().select(lastFileNode)
                if (lastFileNode.data.parentFileId!=null) {
                    var lastParentFileNode = fileStore.findNode('id',lastFileNode.data.parentFileId)
                    file.expandNode(lastParentFileNode)

                }
            }


        },
        select:function() {

        }
    },
    type: 'tree',
    proxy: {
        type: 'ajax',
        url: '../file/store'
    }
})


var editFileTypeStore = Ext.create('Ext.data.Store', {
    autoLoad: true,
    pageSize: 1000,
    remoteSort: true,
    remoteFilter:true,
    listeners:{

    },
    proxy: {
        type: 'ajax',
        url : '../filetype/store?flag=edit',
        reader: {
            type: 'json',
            root: 'results',
            totalProperty: 'total'
        }
    }
});


var file = Ext.create('Ext.tree.Panel', {
    title: '文件列表',
    width: '100%',
    flex:1,
    //height: 300,
    store: fileStore,
    allowDeselect:true,
    scrollable:true,
    reserveScrollbar: true,
    useArrows: true,
    rootVisible: false,
    multiSelect: true,
    singleExpand: false,
    viewConfig:{
        /*plugins :{
            ptype:'treeviewdragdrop',
            appendOnly:true,
            dragText: '移动中'  //dragText: 'Drag and drop to reorganize'       
        },*/
        listeners:{
            rowclick:function( obj, record, element, rowIndex, e, eOpts) {
                //console.log("rowclick")
            },
            rowdblclick:function() {
                //file.setSelection(null)
            },
            select:function( obj, record, index, eOpts ) {
                //console.log("select")
                refreshAction()
            },
            deselect:function( obj, record, index, eOpts ) {
                //console.log("deselect")
                refreshAction()
            },
            containerclick:function() {
                
            },
            drop:function(node,data,overModel,dropPosition,options){
                //console.log("把:"+data.records[0].get('text')+" 移动到："+overModel.get("text"));              
                Ext.Ajax.request({
                    url: "../file/movefile",
                    params: {
                        id:data.records[0].data.id,
                        parentFileId:overModel.data.id
                    },
                    success: function(response, opts) {
                        var res = Ext.JSON.decode(response.responseText)
                        if(res.success) {
                            Ext.toast('移动成功！');
                        } else {
                            alert(res.message);
                            renameFile()
                        }
                    }
                });
            },
            beforedrop:function(node,data,overModel,dropPosition,dropFunction,options){
        
            }
        }
    },
    tbar: [
                { 
                    xtype: 'button', text: '上传文件',id:'btnFileUpload',iconCls:'x-fa fa-upload',disabled:true,
                    handler:function() {
                        
                        $('#fileupload')[0].click()
                    } 
                },
                { 
                    xtype: 'button', text: '新建目录',id:'btnNewDir',iconCls:'x-fa fa-folder',disabled:true,
                    handler:function() {
                        
                        var selection = file.getSelection()
                        var parentFileId
                        if (selection.length!=0) {
                            if (selection[0].data.leaf) {
                                parentFileId = selection[0].data.parentFileId
                            } else {
                                parentFileId = selection[0].data.id
                            }
                        }

                        Ext.MessageBox.prompt('新建目录', '请输入目录名称:', function(btn, text){
                            if (btn=="ok") {
                                if(text==null||text=="") {
                                    Ext.MessageBox.show({
                                        title: '出错!',
                                        msg:"请输入目录名称",
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox["ERROR"]
                                    });
                                    return
                                }
                                
                                Ext.Ajax.request({
                                    url: "../file/mkdir",
                                    params: {
                                        parentFileId:parentFileId,
                                        cnName:text,
                                        meetingId:meeting.getSelection()[0].data.id
                                    },
                                    success: function(response, opts) {
                                        var res = Ext.JSON.decode(response.responseText)
                                        if(res.success) {
                                            Ext.toast('操作成功!');
                                            //lastFileId = res.id
                                            lastFileId = null
                                            console.log(lastFileId)
                                            fileStore.reload()
                                        } else {
                                            Ext.MessageBox.show({
                                                title: '出错!',
                                                msg:res.message,
                                                buttons: Ext.MessageBox.OK,
                                                icon: Ext.MessageBox["ERROR"]
                                            });
                                            
                                        }
                                    }
                                });
                            }
                        }, this);
                        

                        
                    } 
                },
                {
                    xtype: 'button', text: '修改名称',id:'btnFileNameEdit',iconCls:'x-fa fa-pencil',disabled:true,
                    handler:function() {
                        var cnName = file.getSelection()[0].data.cnName.replace(".pdf","")
                        Ext.MessageBox.prompt('修改名称', '请输入新的名称:', function(btn, text){
                            if (btn=="ok") {
                                if(text==null||text=="") {
                                    Ext.MessageBox.show({
                                        title: '出错!',
                                        msg:"请输入名称",
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox["ERROR"]
                                    });
                                    return
                                }

                                Ext.Ajax.request({
                                    url: "../file/rename",
                                    params: {
                                        id:file.getSelection()[0].data.id,
                                        cnName:text
                                    },
                                    success: function(response, opts) {
                                        var res = Ext.JSON.decode(response.responseText)
                                        if(res.success) {
                                            Ext.toast('操作成功!');
                                            lastFileId = res.id
                                            //console.log(lastFileId)
                                            fileStore.reload()
                                        } else {
                                            Ext.MessageBox.show({
                                                title: '出错!',
                                                msg:res.message,
                                                buttons: Ext.MessageBox.OK,
                                                icon: Ext.MessageBox["ERROR"]
                                            });

                                        }
                                    }
                                });
                            }
                        }, this,false,cnName);
                    }
                },
                { 
                    xtype: 'combobox', id:'btnEditFileType',store:editFileTypeStore,editable:false,
                    width:150,displayField:'cnName',valueField:'id',disabled:true,value:-1,
                    listeners:{
                        change:function(obj, newValue, oldValue, eOpts){
                            if (newValue==-1) {
                                //Ext.MessageBox.show({title: '出错!',msg:"请选择文件类型!",buttons: Ext.MessageBox.OK,icon: Ext.MessageBox["ERROR"]});
                                return
                            }
                            var selection = file.getSelection()
                            var ids = []
                            for(var i=0;i<selection.length;i++) {
                                ids.push(selection[i].data.id)
                            }
                            Ext.Ajax.request({
                                url: "../file/updatefiletype",
                                params: {
                                    ids:ids.join(","),
                                    fileTypeId:newValue
                                },
                                success:function(response, opts) {

                                    var res = Ext.JSON.decode(response.responseText)
                                    if(!res.success) {
                                        Ext.MessageBox.show({title: '出错!',msg:res.message,buttons: Ext.MessageBox.OK,icon: Ext.MessageBox["ERROR"]});
                                    } else {
                                        Ext.toast('修改文件类型成功!');
                                        lastFileId = null
                                        fileStore.reload()
                                        Ext.getCmp("btnEditFileType").setValue(-1)
                                        editFileTypeStore.reload()
                                    }

                                }
                            })


                        }
                    }
                },
                { 
                    xtype: 'button', text: '删除',id:'btnFileDelete',iconCls:'x-fa fa-minus',disabled:true,
                    handler:function() {
                        Ext.MessageBox.confirm('确认', '是否删除?', function(btn, text) {
                            if (btn=="yes") {
                                Ext.getCmp("btnEditFileType").disable()
                                Ext.getCmp("btnFileDelete").disable()
                                Ext.getCmp("btnMoveUp").disable()
                                Ext.getCmp("btnMoveDown").disable()
                                Ext.getCmp("btnPassword").disable()
                                Ext.getCmp('btnFileNameEdit').disable()
                                var selection = file.getSelection()
                                var ids = []
                                for(var i=0;i<selection.length;i++) {
                                    ids.push(selection[i].data.id)
                                }
                                Ext.Ajax.request({
                                    url: "../file/delete",
                                    params: {
                                        ids:ids.join(",")
                                    },
                                    success:function(response, opts) {

                                        var res = Ext.JSON.decode(response.responseText)
                                        if(!res.success) {
                                            Ext.MessageBox.show({title: '出错!',msg:res.message,buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox["ERROR"]});
                                        } else {
                                            Ext.toast('删除成功!');
                                            lastFileId = null
                                            fileStore.reload()
                                        }

                                    }
                               })
                            }
                        }, this);    
                    } 
                },
                { 
                    xtype: 'button', text: '上移',id:'btnMoveUp',disabled:true,
                    handler:function() {
                        sortFile("up")
                    } 
                },
                {
                    xtype: 'button', text: '下移',id:'btnMoveDown',disabled:true,
                    handler:function() {
                        sortFile("down")
                    }
                },
                {
                    xtype: 'button', text: '密码',id:'btnPassword',disabled:true,
                    handler:function() {
                        setPassword()
                    }
                },
                {
                    xtype:'container',
                    hidden:true,
                    html:'<span class="btn btn-success fileinput-button" id="fileUploadContainer">上传文件'+
                    '<input id="fileupload" type="file" name="fileupload" multiple></span>',
                    listeners:{
                        render:function( obj, eOpts ) {
                            
                            var url = "../file/upload"
                            $('#fileupload').fileupload({
                                url: url,
                                dataType: 'json',
                                start:function() {
                                    totalSuccessFile = 0
                                    Ext.MessageBox.show({
                                        title: '正在上传文件',
                                        msg: '请稍等...',
                                        progressText: '开始上传...',
                                        width:300,
                                        progress:true,
                                        closable:false
                                    });
                                },
                                stop:function() {
                                    Ext.MessageBox.hide();
                                    Ext.toast(totalSuccessFile+"个文件上传成功")
                                    lastFileId = null
                                    fileStore.reload()
                                },
                                add: function (e, data) {
                                    console.log(data.originalFiles[0].name+" "+(myFLag++))
                                    var flag = true
                                    for (var j=0;j<data.originalFiles.length;j++) {
                                        var filename = data.originalFiles[j].name;
                                        //console.log(filename+" "+(myFLag++))
                                        var acceptFileTypes = /(\.|\/)(pdf)$/i;
                                        if(!checkFileType(filename,acceptFileTypes) && flag==true){
                                            flag = false
                                            break
                                            //return alert("请上传pdf格式的文件");
                                        }
                                    }
                                    
                                    if (flag) {


                                        var meetingId = meeting.getSelection()[0].data.id
                                        var selection = file.getSelection()
                                        var parentFileId 
                                        if (selection.length==0) {
                                            parentFileId = ""
                                        } else {
                                            if (selection[0].data.leaf) {
                                                parentFileId = selection[0].data.parentFileId
                                            } else {
                                                parentFileId = selection[0].data.id
                                            }
                                        }

                                        var url = "../file/upload?meetingId="+meetingId+"&parentFileId="+parentFileId;
                                        data.url = url
                                        //data.formData.meetingId = "ddddd"
                                        data.submit();
                                    } else {
                                        
                                    }
                                   
                                    if (myFLag==data.originalFiles.length) {
                                        myFLag = 0
                                        if (flag==false) {
                                            alert("请上传pdf格式的文件");
                                        }
                                    }
                                   
                                    
                                    
                                },
                                done: function (e, data) {
                                    $.each(data.result.files, function (index, file) {
                                        //$('<p/>').text(file.name).appendTo('#files');
                                    });
                                    totalSuccessFile++
                                    

                                },
                                progressall: function (e, data) {
                                    console.log(data)
                                    var progress = parseInt(data.loaded / data.total * 100, 10);
                                    
                                    Ext.MessageBox.updateProgress(progress/100, progress + '% 已上传');
                                    if (progress==100) {
                                        
                                    }
                                }
                            }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
                        }
                    }
                }
    ],
    columns: [
        {
            xtype: 'treecolumn',
            text: '目录/文件',
            dataIndex: 'cnName',
            sortable:false,
            flex: 1,
            renderer:function(value,metaData,record) {
                //console.log(record.data)
                var cnName = value.replace(".pdf","")
                if (!record.data.leaf) {
                    if(record.data.password!=null&&record.data.password!="") {
                        return cnName+"<font style='color:red'>*</font>"
                    } else {
                        return cnName
                    }

                } else {
                    var pdfUrl = "../static/pdf/"+record.data.fileUuid+".pdf"
                    //console.log(pdfUrl)
                    if(record.data.password!=null&&record.data.password!="") {
                        return "<a target='_blank' href='"+pdfUrl+"'>"+cnName+"</a>"+"<font style='color:red'>*</font>"
                    } else {
                        return "<a target='_blank' href='"+pdfUrl+"'>"+cnName+"</a>"
                    }

                }

            }
        },
        {
            text: '类型',
            dataIndex: 'fileTypeId',
            sortable:false,
            flex: 1,
            renderer:function(value,metaData,record) {
                if (value==null||value=="") {
                    return ""
                } else {
                    return fileTypes[value+""]
                }

            }
        },
        {
            text: '上传时间',
            dataIndex: 'dateCreated',
            sortable:false,
            flex: 1,
            xtype: 'datecolumn',
            format: 'Y-m-d H:i'
        }
    ]
                   
});

